package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;

    /**
     * 下单秒杀券
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //没查到直接报错
        if (voucher==null) return Result.fail("秒杀券id错误！");
        //2.判断秒杀是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now()) || voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("不在活动时间内！");
        }
        //3.判断库存是否充足
        if (voucher.getStock()<1)  return Result.fail("库存不足！");

        //使用悲观锁和事务实现一人一单  【细节！悲观锁套事务，而不是锁套悲观锁】（因为事务的底层原理是先打包好方法内的东西，在交给spring托管提交至数据库，如果交给spring期间有别的线程也提交了事务就会重复操作）
        //用每个用户的id作为锁，保证一人一单
        UserDTO userId = UserHolder.getUser();
        synchronized (userId.toString().intern()) { //悲观锁
            //获取代理对象（保证事务有效）
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId); //方法使用了事务
        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        // x.一人一单
        Long userId = UserHolder.getUser().getId();
        // x.1.查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // x.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            return Result.fail("用户已经购买过一次！");
        }

        //4.有库存就减少库存并下单【乐观锁实现不超单】
        boolean flag = seckillVoucherService.update()
                .setSql("stock= stock -1")
                .eq("voucher_id", voucherId)
                .gt("stock",0).update(); //where id = ? and stock > 0
        //下单失败
        if (!flag) return Result.fail("库存不足！");
        //5.下单成功创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //使用redis产生订单唯一id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //设置下单的用户id
        voucherOrder.setUserId(userId);
        //代金券id
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        //返回订单id
        return Result.ok(orderId);
    }
}
